<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <div style="margin-top: 15px;">
      <el-input
        placeholder="请输入内容"
        v-model="userobj.query"
        class="input-with-select"
        style="width:300px;margin-right:10px "
        @keydown.enter.native="init"
      >
        <el-button slot="append" icon="el-icon-search" @click="init"></el-button>
      </el-input>
      <!-- <el-button type="success" round @click="adddialogVisible = true">增加用户</el-button> -->
      <el-button type="success" round @click="adddialogVisible = true">增加用户</el-button>

      <!-- 增加用户弹出框 -->
      <el-dialog
        title="新增用户"
        :visible.sync="adddialogVisible"
        width="50%"
        :before-close="handleClose"
      >
        <!-- 这里是对话框填写的内容 -->
        <el-form :model="addform " :rules="rules" ref="userFrom" :label-width="'80px'">
          <!-- <el-form :model="addform"  :label-width="'80px'"> -->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addform.username" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addform.password" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addform.email" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="addform.mobile" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addclean">取 消</el-button>
          <el-button type="primary" @click="addsubmit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 表格 -->
    <el-table :data="userList" style="width: 100%" border>
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column label="用户状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="editUserstatus(scope.row.id,scope.row.mg_state)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top-end">
            <el-button type="success" icon="el-icon-edit" @click="showedit(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top-end">
            <el-button type="primary" icon="el-icon-share" @click="showgrant(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top-end">
            <el-button type="danger" icon="el-icon-delete" @click="deltUserById(scope.row.id)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="userobj.pagenum"
      :page-sizes="[1, 2, 5, 6]"
      :page-size="userobj.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 编辑用户弹出对话框 -->
    <!-- <el-button type="text" @click="editdialogFormVisible = true">编辑用户信息</el-button> -->

    <el-dialog title="编辑用户" :visible.sync="editdialogFormVisible">
      <el-form :model="editFrom" :label-width="'80px'" :rules="rules" ref="editFrom">
        <el-form-item label="用户名">
          <el-input v-model="editFrom.username" auto-complete="off" disabled style="width:100px"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editFrom.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editFrom.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserById">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="grantdialogFormVisible">
      <el-form :model="grantform" :label-width="'80px'">
        <el-form-item label="用户名">
          <el-input v-model="grantform.username" auto-complete="off" disabled style="width:100px"></el-input>
        </el-form-item>
        <el-form-item label="角色选择">
          <el-select v-model="grantform.rid" placeholder="请选择">
            <el-option
              v-for="item in RoleList"
              :key="item.value"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantUserRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 引入用户信息请求方法
import {
  getAllUsers,
  addUsers,
  editUserById,
  deltUserById,
  editUserstatus,
  grantUserRole
} from '@/api/users_index.js'
// 引入角色信息请求方法

import { getAllroleList } from '@/api/role_index.js'

export default {
  data () {
    return {
      grantdialogFormVisible: false,
      RoleList: [],
      grantform: {
        username: '',
        id: '',
        rid: ''
      },
      editFrom: {
        username: '',
        id: '',
        email: '',
        mobile: ''
      },
      addform: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editdialogFormVisible: false,
      adddialogVisible: false,
      total: 0,
      // currentPage: '',
      userobj: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { pattern: /\w+[@]\w+[.]\w+/, message: '请输入合法的电子邮箱', trigger: 'blur' }
        // { pattern: /\w+[@]\w+[.]\w+/, message: '请输入合法的电子邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '请输入合法的电子邮箱', trigger: 'blur' }

        ]
      }
    }
  },
  methods: {
    // 实现角色分配修改
    grantUserRole () {
      console.log(this.grantForm)
      if (this.grantform.rid) {
        grantUserRole(this.grantform)
          .then(res => {
            if (res.data.meta.status === 200) {
              console.log(res)
              this.$message({
                type: 'success',
                message: '修改角色成功!'
              })
              this.grantdialogFormVisible = false
              // this.init()
            } else {
              this.$message({
                type: 'error',
                message: res.data.meta.msg
              })
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '修改角色失败'
            })
          })
      } else {
        this.$message({
          type: 'errr',
          message: '请选择角色'
        })
      }
    },
    // 显示默认数据
    showgrant (row) {
      // this.grantdialogFormVisible:true
      this.grantdialogFormVisible = true
      this.grantform.username = row.username
      this.grantform.id = row.id
      this.grantform.rid = row.rid
    },

    // 修改用户状态
    editUserstatus (uid, type) {
      editUserstatus(uid, type)
        .then(res => {
          if (res.data.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '修改状态成功!'
            })
            this.init()
          } else {
            this.$message({
              type: 'error',
              message: res.data.meta.msg
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '修改状态失败'
          })
        })
    },
    // 删除单个用户
    deltUserById (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(res => {
          deltUserById(id)
            .then(res => {
              if (res.data.meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.init()
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.meta.msg
                })
              }
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '删除失败'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击对话框的确定进行编辑提交
    editUserById () {
      editUserById(this.editFrom)
        .then(res => {
          if (res.data.meta.status === 200) {
            console.log(res)
            this.editdialogFormVisible = false
            this.$message.success('用户编辑成功')
            // 刷新数据
            this.init()
            // 清空表单
            this.$refs.editFrom.resetFields()
          }
        })
        .catch(() => {
          this.$message.success('用户编辑失败')
        })
    },

    // 获去id默认展示数据
    showedit (row) {
      // console.log(row)
      this.editdialogFormVisible = true
      this.editFrom.id = row.id
      this.editFrom.username = row.username
      this.editFrom.email = row.email
      this.editFrom.mobile = row.mobile
    },
    // 这里是获取全部用户
    init () {
      getAllUsers(this.userobj)
        .then(res => {
          console.log(res)
          // 给数据给表格源
          this.userList = res.data.data.users
          // 拿到总记录数
          this.total = res.data.data.total
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 这里是分页的触发事件处理
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      // if (val === 1) {
      this.userobj.pagesize = val
      this.init()
      // }
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.userobj.pagenum = val
      this.init()
    },
    addsubmit () {
      // 二次验证
      this.$refs.userFrom.validate(valid => {
        if (valid) {
          addUsers(this.addform)
            .then(res => {
              if (res.data.meta.status === 201) {
                this.$message({
                  type: 'success',
                  message: '数据新增成功'
                })
                // 重新刷新
                this.init()
                // 关闭对话框
                this.adddialogVisible = false
                // 重置对话框
                this.$refs.userFrom.resetFields()
              } else {
                this.$message({
                  message: res.data.meta.msg
                })
              }
            })
            .catch(() => {
              this.$message({
                message: '服务器异常，请稍后重试',
                type: 'warning'
              })
              // console.log(err)
            })
        } else {
          this.$message({
            type: 'error',
            message: '数据输入不合法'
          })
          return false
        }
      })
    },

    // 这里是新增用户
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.$refs.userFrom.resetFields()
          done()
        })
        .catch(_ => {})
    },
    // 取消时把数据清空和关闭对话框
    addclean () {
      this.adddialogVisible = false
      this.$refs.userFrom.resetFields()
    }
  },
  // 组件进入就触发获取用户数据
  mounted () {
    this.init()
    // 获取全部角色信息
    getAllroleList()
      .then((res) => {
        console.log(res)

        if (res.data.meta.status === 200) {
          this.RoleList = res.data.data
        }
        console.log(this.RoleList)
      })
      .catch(() => {
        console.log('角色查询失败')
      })
  }
}
</script>
<style lang='less' scoped>
</style>
